<!--
* @author wn
* @date 2022/10/09 15:05:14
* @description: 用户管理
!-->
<template>
	<div class="app-user">
		<!-- user头部 新增  搜索 组件-->
		<div class="user-header">
			<el-button type="primary" @click="onInsertClick">+新增</el-button>
			<el-form :inline="true" :model="formData">
				<el-form-item label="请输入">
					<el-input v-model="formData.userName" placeholder="请输入用户名" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="onSearch">搜索</el-button>
				</el-form-item>
			</el-form>
		</div>
		<!-- @row-click="onRowClick" -->
		<el-table
			:data="tabList"
			height="600"
			stripe
			border
			header-cell-class-name="table-header"
			style="width: 100%"
		>
			<el-table-column
				v-for="item in userTable"
				:key="item.prop"
				:prop="item.prop"
				:label="item.label"
				:width="item.width ? item.width : 180"
				align="center"
			/>
			<el-table-column fixed="right" label="操作" min-width="1" align="left">
				<template #default="scope">
					<el-button
						size="small"
						class="btn-edit"
						@click="handleEdit(scope.row)"
					>
						编辑
					</el-button>
					<el-button
						type="danger"
						size="small"
						@click="handleDelete(scope.row)"
					>
						删除
					</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 分页组件
			@current-change="handleCurrentChange"
		@size-change="handleSizeChange"-->
		<div class="pagination">
			<el-pagination
				v-model:currentPage="page"
				v-model:page-size="limit"
				:page-sizes="[10, 20, 30, 40]"
				:total="total"
				layout="total, sizes,prev, pager, next"
				:pager-count="6"
				background
			/>
		</div>
		<!-- 添加用户 对话框 -->
		<el-dialog
			v-model="dialogVisible"
			:title="title"
			:before-close="handleBeforeClose"
			width="35%"
			center
			draggable
		>
			<el-form
				:model="userData"
				ref="ruleForm"
				:rules="rules"
				status-icon
				label-position="right"
				label-width="80px"
			>
				<el-row :gutter="2">
					<el-col :span="12">
						<el-form-item label="姓名" prop="name">
							<el-input v-model="userData.name" placeholder="请输入姓名" />
						</el-form-item>
						<el-form-item label="性别" prop="sexLabel">
							<el-select v-model="userData.sexLabel" placeholder="请选择性别">
								<el-option label="男" value="男" />
								<el-option label="女" value="女" />
							</el-select>
						</el-form-item>
						<el-form-item label="出生日期" prop="birth">
							<el-date-picker
								v-model="userData.birth"
								type="date"
								placeholder="请选择日期"
								value-format="YYYY-MM-DD"
								:disabled-date="disabledDate"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="年龄" prop="age">
							<el-input
								v-model.number="userData.age"
								placeholder="请输入年龄"
							/>
						</el-form-item>
						<el-form-item label="地址" prop="addr">
							<el-input v-model="userData.addr" placeholder="请输入地址" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="handleClose">取消</el-button>
					<el-button type="primary" @click="handleConfirm"> 确认 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>
<script setup>
// 用户 table 数据
import { getUserTableData, userTable } from '@/network/user'
import { nextTick, reactive, ref, toRefs, watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
// 校验规则
import rules from '@/utils/el-validate-schema'
/**
 * 查询条件
 * 默认 第一页  20条数据
 */
const query = reactive({
	page: 1, // 是 1 页码
	limit: 20, // 是 10 页尺寸
})
const { page, limit } = toRefs(query)
// 总页码
const total = ref(0)
// 获取 table 数据  分页  page=1 limit = 20
const tabList = ref(null)

// 获取 数据 按照 查询  分页 筛选数据
const useGetUserTableData = async () => {
	const { result } = await getUserTableData()
	// 手动 截取 第一页  20 条数据
	const searchData = result.filter(v => v.name.search(formData.userName) !== -1)
	const pageData = searchData.filter(
		(item, index) =>
			index &&
			index > (query.page - 1) * query.limit &&
			index <= query.page * query.limit
	)
	tabList.value = pageData.map(v => {
		v.sexLabel = v.sex === 0 ? '女' : '男'
		return v
	})
	total.value = searchData.length
}

watch(
	query,
	() => {
		useGetUserTableData()
	},
	{ immediate: true }
)
/* // 分页组件  点击事件
const handleCurrentChange = v => {
	query.page = v
}
// 更改 limit 触发事件
const handleSizeChange = v => (query.limit = v) */

// 头部 新增  查询
const formData = reactive({
	userName: undefined,
})
const onSearch = () => {
	if (formData.userName === undefined) return
	useGetUserTableData()
	formData.userName === '' && (formData.userName = undefined)
}

// 对话框
const title = ref('新增用户')
const dialogVisible = ref(false)
// 表单实例
const ruleForm = ref(null)
const userData = reactive({
	id: '',
	name: '',
	age: '',
	sexLabel: '',
	birth: '',
	addr: '',
})
// 新增按钮点击事件
const onInsertClick = () => {
	title.value = '新增用户'
	dialogVisible.value = true
}
// 点击  关闭按钮 或者对话框的  遮罩区域  时被调用
// 可以在 footer  中 关闭 加入 该逻辑
const handleBeforeClose = async done => {
	try {
		await ElMessageBox.confirm(
			'你确定关闭该对话框么 目前只针对 关闭按钮和遮罩层'
		)
		// done()
		handleClose()
	} catch (error) {
		// catch error
	}
}
// 之后的时间不可选
const disabledDate = time => time.getTime() > Date.now()

// 校验规则
// 取消 关闭对话框 清空数据  清空校验规则 resetFields 两件都干了
const handleClose = () => {
	dialogVisible.value = false
	ruleForm.value.resetFields()
}
// 确认 关闭对话框 插入数据
const handleConfirm = async () => {
	// 校验
	await ruleForm.value.validate((valid, fields) => {
		if (valid) {
			// 插入 原数据显示  结束后 v-model 绑定 会 resetFields 清空 堆地址一样
			if (title.value === '新增用户') {
				const showData = Object.assign({}, userData)
				tabList.value.pop()
				tabList.value.unshift(showData)
			} else {
				// 编辑状态
				const current = tabList.value.find(item => item.id === userData.id)
				Object.assign(current, userData)
			}
			handleClose()
		} else {
			// fields  只包含未验证 字段
			ElMessage({
				showClose: true,
				message: '请输入正确内容',
				type: 'error',
			})
		}
	})
}

// 编辑 点击 获取 当前 行数据  赋值给  userData 其余 与 打开对话框 一致
// #default="scope" .row 自定义列 获取
/* const onRowClick = (row, column, event) => {
	for (const key in userData) {
		userData[key] = row[key]
	}
} */

/**
 * 是否是 编辑
 * 1 对话框 关闭时  无论是  确认 还是  取消  都执行了 resetFields  所以 新增时无需
 * 2 handleEdit 中 直接 赋值 userData 在 虚拟DOM中 beforeCreated 相当于修改了 userData 的初始值
 * 3 resetFields  就是复原初始值  所以 数据 不会清空  初始值不是空
 * 4 nextTick 中修改  是 mounted 后  不会修改初始值  异步中也同理
 */
const handleEdit = row => {
	title.value = '编辑用户'
	dialogVisible.value = true
	nextTick(() => {
		Object.assign(userData, row)
	})
}
// 删除按钮
const handleDelete = async row => {
	try {
		await ElMessageBox.confirm('确定删除该用户么')
		tabList.value = tabList.value.filter(item => item.id !== row.id)
		ElMessage({
			showClose: true,
			message: '删除成功',
			type: 'success',
		})
	} catch (error) {
		// catch error
	}
}
</script>
<style scoped lang="scss">
.app-user {
	background-color: #fff;
	.el-table {
		:deep(.table-header) {
			color: #8c99ff;
			background-color: #f0f2ff !important;
			&:last-child {
				padding-left: 86px;
			}
		}
		:deep(th) {
			height: 60px;
		}
		.btn-edit {
			margin: 0 30px;
		}
	}
	.pagination {
		display: flex;
		justify-content: center;
		padding: 30px;
		// 点击无边框  点击选中无边框
		:deep(li) {
			outline: none;
		}
	}
	.user-header {
		display: flex;
		justify-content: space-between;
		padding: 20px 60px 2px;
	}
	// style="width: 100%"
	.el-select,
	:deep(.el-date-editor) {
		width: 100%;
	}
}
</style>
